import _ from 'lodash'
import {Message} from 'element-ui'
import axios from 'axios'
import router from '@/router'
import store from '@/store'

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000
})

const showErrMsg = _.debounce(function (msg){
  Message.error(msg)
}, 1000)

// 请求拦截器
service.interceptors.request.use(
  config => {
    // config.headers['token'] = store.getters['user/token']
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    if (response.status === 200) {
      const {code, msg} = response.data
      switch (Number(code)) {
        // code1
        case 1:
          showErrMsg(msg)
          return Promise.reject(response.data)

        case 401:
        case 403:
          showErrMsg('登录已过期')
          // 清除本地用户状态
          store.commit('user/SET_LOGOUT')
          // 跳转到登录页面
          router.push({name: 'login'})
          return Promise.reject(response.data)

        // 默认
        default:
          return response.data
      }
    } else {
      return Promise.reject(response.data)
    }
  },
  error => {
    showErrMsg('连接超时')
    return Promise.reject(error)
  }
)

export default service
